package com.mes.web.controller.tdd;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.google.gson.Gson;
import com.mes.entity.tdd.Department;
import com.mes.entity.tdd.Staff;
import com.mes.entity.tdd.tj.Tpage;
import com.mes.service.tdd.DepartmentService;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ExcelUtils;
import com.mes.utils.ResponseUtil;
import com.mes.utils.StringUtil;
/**
 * 
 *@ClassName: DepartmentController 
 *@Description: 部门
 *@Author tdd
 *@Date 2018-6-5 上午11:33:25 
 *@version 1.0
 */
@Controller
@RequestMapping("/department")
public class DepartmentController {
	//引入部门的service
	@Resource public DepartmentService departmentService;
	/**
	 * 部门分页列表查询
	 * @param pageBean
	 * @param limit
	 * @param offset
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/list")
	public void materieDemandList(HttpServletRequest request,Tpage pageBean,@RequestParam(value="limit",required=false)String limit,@RequestParam(value="offset",required=false)String offset,HttpServletResponse response) throws Exception {
		/*String departmentname = request.getParameter("departmentname"); 
		if(null != departmentname && !departmentname.equals("")){
			departmentname = new String(departmentname.getBytes("iso8859-1"),"utf-8");
			pageBean.setStaffname(departmentname);
		}
		String deenter = request.getParameter("deenter"); 
		if(null != deenter && !deenter.equals("")){
			deenter = new String(deenter.getBytes("iso8859-1"),"utf-8");
			pageBean.setStaffname(deenter);
		}*/
		//页数
		pageBean.setPage(Integer.parseInt(offset)/Integer.parseInt(limit));
		//每页条数
		pageBean.setPageSize(Integer.parseInt(limit));
		//未删除
		pageBean.setIsdelete("0");
		List<Department> departments=departmentService.list(pageBean);
		int total=departmentService.total(pageBean);
		
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(departments, jsonConfig);
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}
	
	
	/**
	 * 部门查询所有
	 * @param pageBean
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/all")
	public void materieDemandAll(Tpage pageBean,HttpServletResponse response) throws Exception {
		//未删除
		pageBean.setIsdelete("0");
		List<Department> departments=departmentService.all(pageBean);
		Gson gson = new Gson();
		ResponseUtil.write(response, gson.toJson(departments));
	}
	
	
	
	
	/**
	 * 添加部门信息
	 * @param response
	 * @param department
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping("/add")
	public void add(HttpServletResponse response,Department department,HttpServletRequest request) throws IOException{
		//判断session
        HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        Staff userSession = (Staff) session.getAttribute("staff");
        //当前时间
        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        String   date   =   sDateFormat.format(new Date());
        //根据部门名称查部门
        Tpage pageBean = new Tpage();
        pageBean.setDepartmentname(department.getDepartmentname());
        pageBean.setIsdelete("0");
        List<Department> total = departmentService.all(pageBean);
    	//判断编号是否重复
		//编号重复
		if (total.size()>0) {
			response.getWriter().print("-1");
		//编号不重复
		}else{
        	//添加库区
        	//录入人
			department.setDeenter(userSession.getStaffname());
        	//录入时间
			department.setDeentertime(date);
        	//是否删除标识，未删除
			department.setIsdelete("0");
        	//添加
        	Long id = departmentService.add(department);
        	//添加成功
        	if (null != id && id >= 1) {
        		response.getWriter().print("1");
        		//未成功
        	} else {
        		response.getWriter().print("0");
        	}
		}
	}
	/**
	 * 到修改
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toupdate")
	public String toupdata(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//json
		Gson gson=new Gson();
		//根据id查询数据
		Tpage pageBean = new Tpage();
		//获取id
		pageBean.setDepartmentid(Long.valueOf((Integer.parseInt(request.getParameter("departmentid")))));
		//未删除
		pageBean.setIsdelete("0");
		List<Department> list = departmentService.all(pageBean);
		//获得数据
		if (list.size()>0) {
			//传递数据到页面
			ResponseUtil.write(response, gson.toJson(list.get(0)));
		}
		//跳转到修改页面
		return null;
	}
	/**
	 * 修改
	 * @param department
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping("/update")
	public void updata(Department department,HttpServletResponse response,HttpServletRequest request) throws IOException{
		//判断session
       HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        Staff userSession = (Staff) session.getAttribute("staff");
        //当前时间
        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        String   date   =   sDateFormat.format(new Date());
		//修改
        //录入人
        department.setDeenter(userSession.getStaffname());
    	//录入时间
        department.setDeentertime(date);
    	//是否删除标识，未删除
        department.setIsdelete("0");
		
		//根据id查数据
        //修改前数据
    	Tpage pageBean = new Tpage();
		//获取id
		pageBean.setDepartmentid(department.getDepartmentid());
		//未删除
		pageBean.setIsdelete("0");
		List<Department> list = departmentService.list(pageBean);
		//如果有该条数据
		if (list.size()>0) {
			//编号是否重复标识
			  //根据编号查所有库区
	        Tpage page = new Tpage();
	        page.setIsdelete("0");
	        page.setDepartmentname(department.getDepartmentname());
			List<Department> departments = departmentService.all(page);
	    	//判断编号是否重复
			int num = 0;
			//编号重复
	        for (int i = 0; i < departments.size(); i++) {
	        	//判断编号是否重复
				if (department.getDepartmentname().equals(departments.get(i).getDepartmentname()) && !list.get(0).getDepartmentname().equals(departments.get(i).getDepartmentname())) {
					num++;
				}
			}
	      //编号不重复
	        if (num <= 0) {
	        	//修改
				int n = departmentService.updata(department);
				//修改成功
				if (n >= 1) {
					response.getWriter().print("1");
					//未成功
				} else {
					response.getWriter().print("0");
				}
			}else {
				//编号重复
				response.getWriter().print("-1");
			}
		//如果没有该条数据(没有)
		}else {
			//该数据不存在
			response.getWriter().print("2");
		}
	}
	/**
	 * 删除
	 * @param ids
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletRequest request,HttpServletResponse response) throws Exception{
		//判断session
        HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        Staff userSession = (Staff) session.getAttribute("staff");
        //当前时间
        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        String   date   =   sDateFormat.format(new Date());
        List<Long> listId = StringUtil.splitListL(ids, ",");
        for (int i = 0; i < listId.size(); i++) {
        	//根据id查数据
        	//修改前数据
        	Tpage pageBean = new Tpage();
        	//获取id
        	pageBean.setDepartmentid(listId.get(i));
        	//未删除
        	pageBean.setIsdelete("0");
        	List<Department> list = departmentService.all(pageBean);
        	//如果有该条数据
        	if (list.size()>0) {
        		Department department = list.get(0);
        		/* //录入人
	    	staff.setStenter(userSession.getStaffname());
	    	//录入时间
	    	staff.setStentertime(date);*/
        		//是否删除指定删除
        		department.setIsdelete("1");
        		//删除（假删除）
        		int n = departmentService.updatadelete(department);
        		//删除成功
        		if (n >= 1) {
        			//未成功
        		} else {
        			response.getWriter().print("0");
        		}
        		//如果没有该条数据(没有)
        	}else {
        		//该数据不存在
        		response.getWriter().print("2");
        	}
		}
        response.getWriter().print("1");
	}	
	
	
	
	
	/**
	 * 导出模板
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExportFile")
	public void doExportFile(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ExcelUtils.exportFile("部门导入模板",names(), response);
	}	
	
	/**
	 * 导出当前页数据
	 * @param pageBean
	 * @param limit
	 * @param offset
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExport")
	public void doExport(Tpage pageBean,@RequestParam(value="limit",required=false)String limit,@RequestParam(value="offset",required=false)String offset,HttpServletResponse response) throws Exception {
		//页数
		pageBean.setPage(Integer.parseInt(offset)/Integer.parseInt(limit));
		//每页条数
		pageBean.setPageSize(Integer.parseInt(limit));
		//未删除
		pageBean.setIsdelete("0");
		List<Department> departments=departmentService.list(pageBean);
		List<List<String>> lists = departmentzhuanlist(departments);
		ExcelUtils.export("部门当前数据",namess(), response,lists );
	}	
	/**
	 * 导出所有数据
	 * @param pageBean
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExportall")
	public void doExportall(Tpage pageBean,HttpServletRequest request,HttpServletResponse response) throws Exception{
		//未删除
		pageBean.setIsdelete("0");
		List<Department> departments=departmentService.all(pageBean);
		List<List<String>> lists = departmentzhuanlist(departments);
		ExcelUtils.export("部门所有数据",namess(), response,lists);
	}	
	
	
	/**
	 * 导入
	 * @param file
	 * @param request
	 * @param response
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException{
		   String savePath = ((HttpSession) request).getServletContext().getRealPath("/WEB-INF/"+file.getOriginalFilename());
		   File newFile=new File(savePath);
		   //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	       file.transferTo(newFile);
	       //取文件后缀
	       String subfix = savePath.lastIndexOf(".")==-1? "" : savePath.substring(savePath.lastIndexOf(".")+1);
	       System.out.println(subfix);
	       List<List<String>> lists = new ArrayList<>();
	       //获取导入行数
	       List<String> names = names();
	       int num = names.size();
	       String xls = "xls";
	       String xlsx = "xlsx";
	       if(xls.equals(subfix)){
	    	   lists = ExcelUtils.readXls(savePath, request,num);
	 	   }else if(xlsx.equals(subfix)){
	 		   lists = ExcelUtils.readXlsx(savePath, request,num);
	 	   }else{
	 	   		response.getWriter().print("0");
	 	   }
	       
	       /*HttpSession session  = request.getSession();
	        //从session中取出用户身份信息
	       Staff userSession = (Staff) session.getAttribute("staff");*/
	       String staffname = null;
	       SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
	       String   date   =   sDateFormat.format(new Date());
	       
	       int flag = 1; 
	       for (int i = 0; i < lists.size(); i++) {
	    	   List<String> list = new ArrayList<>();
	    	   list= lists.get(i);
	    
	    	   Department department =new Department();
	    	   department.setDepartmentname(list.get(0));
	    	   department.setDeremark(list.get(1));
	    	
	    	   int ff = adddepartment(department, request, date, staffname);
	    	   department = null;
	    	   if (ff == 0) {
	    		   flag = 0;
	    		   break;
	    	   }
	       }
	       response.getWriter().print(flag);
	 }
	/**
	 * 导出模板的表头
	 * @return
	 */
	public List<String> names(){
		List<String> list = new ArrayList<>();
		list.add("部门名称");
		list.add("备注");
		return list;
	}
	/**
	 * 导出数据表头
	 * @return
	 */
	public List<String> namess(){
		List<String> list = new ArrayList<>();
		list.add("部门名称");
		list.add("备注");
		list.add("录入人");
		list.add("录入时间");
		return list;
	}
	/**
	 * 根据导出数据表头把List<Staff>转List<List<String>>
	 * @param staffs
	 * @return
	 */
	public List<List<String>> departmentzhuanlist (List<Department> departments){
		List<List<String>> lists = new ArrayList<>();
		for (Department department : departments) {
			List<String> list = new ArrayList<>();
			list.add(department.getDepartmentname());
			list.add(department.getDeremark());
			list.add(department.getDeenter());
			list.add(department.getDeentertime());
			lists.add(list);
			list = null;
		}
		return lists;
	}
	/**
	 * 导入数据是的添加方法（如果不满足添加条件，直接过滤）
	 * @param staff
	 * @param request
	 * @param date
	 * @param staffname
	 * @return
	 */
	public int adddepartment(Department department,
			HttpServletRequest request,String date,String staffname){
		int flag = 0;
     
        //根据部门名称查部门
        Tpage pageBean = new Tpage();
        pageBean.setDepartmentname(department.getDepartmentname());
        pageBean.setIsdelete("0");
        List<Department> total = departmentService.all(pageBean);
    	//根据编号查出部门个数是否大于0判断编号是否重复
		//编号查出部门个数大于0编号重复
		if (total.size()>0) {
			flag = 1;
		//编号不重复
		}else{
        	//添加库区
        	//录入人
			department.setDeenter(staffname);
        	//录入时间
			department.setDeentertime(date);
        	//是否删除标识，未删除
			department.setIsdelete("0");
        	//添加
        	Long id = departmentService.add(department);
        	//添加成功
        	if (null != id && id >= 1) {
        		flag = 1;
        		//未成功
        	} else {
        		flag = 0;
        	}
		}
		return flag;
	}
}
